#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)

source("cueing_functions.R")

## This setup allows the function to be called from the
#  command line, making it easy to experiment with
## other thresholds for cocs and oppcs.
cocs <- as.numeric(args[1])
oppcs <- as.numeric(args[2])

# Set up data for use with ASA standard errors
exit_x <- read.csv(paste0("exit_cueing_data1616splitweighted.csv"))
exit_x$deltay <- (exit_x$agree2 - exit_x$agree1)
exit_x$friend <- apply(cbind(exit_x$copartisans, exit_x$cs), 1, 
                  function(z) ifelse(z[1] == 1, ifelse(z[2] >= cocs, 1, 0), 
                                     ifelse(z[2] >= oppcs, 1, 0)))

exit_x$legA2 <- apply(exit_x, 1, function(z) paste0(z[16], z[7]))
exit_x$legB2 <- apply(exit_x, 1, function(z) paste0(z[17], z[7]))

Aind <- which(colnames(exit_x) == "legA2")
Bind <- which(colnames(exit_x) == "legB2")

exit_x$dyads <- apply(exit_x, 1, function(r) paste0(r[Aind], "-", r[Bind]))

# Model is here 
fmla <- formula(deltay ~ treat + friend +
                  I(treat * friend) + I(treat * copartisans) + 
                  I(friend * copartisans) + 
                  #I(sgcs + ogcs) + I(sfcs + ofcs) + 
                  #I(treat * (sgcs + ogcs)) +
                  #I(treat * (sfcs + ofcs)) + 
                  sgcs + I(treat * sgcs) +
                  ogcs + I(treat * ogcs) + 
                  sfcs + I(treat * sfcs) + 
                  ofcs + I(treat * ofcs) +
                  interaction(factor(congress), committee,
                              leg_party, copartisans) +
                  n1 + n2)

exit_fit <- lm(fmla, data = exit_x, weights = exit_x$weights)
coef(exit_fit)[1:14]
coef(exit_fit)[1:14]/sqrt(diag(vcov(exit_fit))[1:14])

exit_index <- unique(c(as.character(exit_x$legA2), as.character(exit_x$legB2)))
exit_dyad.mat <- apply(exit_x[,c(Aind, Bind)], 2, as.character)

## You will need access to a cluster computer to calculate the standard errors
cl <- makeCluster(32)
registerDoSNOW(cl)
exit_dyad.vcov <- dyad.robust.se(exit_x, exit_fit, exit_index, exit_dyad.mat)
stopCluster(cl)

exit_fit <- lm(fmla, data = exit_x, weights = exit_x$weights, qr = FALSE)

# Store with qr = FALSE to save memory
save.image(paste0("exit_cueingresults_", cocs, oppcs, ".RData"))
